import { defineComponent, ref } from "vue";
import calendar, { RENDER_WEEK_NAME_MAP, DayType } from "./calendar-class";
import MyButton from "../button/button";

/** 渲染星期 */
const renderWeek = () => {
  return (
    <div class="my-calendar__title">
      {RENDER_WEEK_NAME_MAP.map((item) => (
        <span class="my-calendar-week">{item}</span>
      ))}
    </div>
  );
};

/** 渲染day */
const renderDate = (list: Array<DayType>) => {
  /** 渲染动态样式 */
  const classes = (item: DayType) => {
    return {
      "my-calendar-day": true,
      "is-selected": item.isToday,
    };
  };

  return (
    <div class="my-calendar__body">
      {list.map((item) => (
        <span class={classes(item)}>{item.day || ""}</span>
      ))}
    </div>
  );
};

/** 日期转换成年月 */
const dateToYearAndMonth = (val: Date | string | number | undefined) => {
  // 判断值是否存在
  if (!val) {
    throw new Error("invalid val");
  }

  // 转成Date 类型
  const data = val instanceof Date ? val : new Date(val);
  const year = data.getFullYear();
  const month = data.getMonth() + 1;
  return { year, month };
};

/** 组件页面，输出组件demo */
export default defineComponent({
  name: "MyCalendar",
  props: {
    // eslint-disable-next-line vue/require-default-prop
    modelValue: [String, Number, Date],
  },
  emits: ["update:modelValue"],
  setup(props, { emit }) {
    const dataList = ref();
    const dataTime = ref();

    // 获取当前天数
    const currentData = dateToYearAndMonth(props.modelValue);
    const calen = new calendar(
      (list, data) => {
        // 这里可以添加业务处理函数
        const newList = list.map((item) => ({ ...item, a: false }));
        dataList.value = newList;
        dataTime.value = data;

        emit("update:modelValue", new Date());
        return newList;
      },
      currentData.year,
      currentData.month
    );

    /** 渲染函数 */
    return () => (
      <div class="my-calendar">
        <div class="my-calendar__header">
          <div>{dataTime.value.year + "年" + dataTime.value.month + "月"}</div>
          <div>
            <MyButton
              type="primary"
              onClick={() => calen.handlePrevMonthClick()}
            >
              上月
            </MyButton>
            <MyButton
              type="primary"
              onClick={() => calen.handleNextMonthClick()}
            >
              下月
            </MyButton>
          </div>
        </div>
        {/* 星期 */}
        {renderWeek()}

        {/* 日历 */}
        {renderDate(dataList.value)}
      </div>
    );
  },
});
